<template>
  <div class="container">
    <el-dialog :title="showTitle" :visible="showEditAddDialog" @close="btnCancel">
      <el-form label-width="100px" :model="article" :rules="rules" ref="articleForm">
        <el-form-item label="文章标题:" size="small" prop="title">
          <el-input
            placeholder="请输入文章标签"
            v-model.trim="article.title"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章内容:" class="quill-editor" prop="articleBody">
          <quill-editor
            v-model.trim="article.articleBody"
            ref="myQuillEditor"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
        <el-form-item label="视频地址:" size="small">
          <el-input
            placeholder="请输入视频地址"
            v-model.trim="article.videoURL"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-row slot="footer" type="flex" justify="end">
        <el-button @click="btnCancel">取消</el-button>
        <el-button type="primary" @click="btnOk">确认</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.snow.css'
import { add, update } from '@/api/hmmm/articles'
export default {
  components: {
    quillEditor
  },
  props: {
    showEditAddDialog: {
      type: Boolean,
      default: false
    },
    article: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      editorOption: { // 定义富文本编辑器显示
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗、倾斜、下划线、删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'],
            ['code-block', 'image', 'link']
          ]
        },
        placeholder: ''

      },
      rules: {
        title: [{ required: true, message: '请输入文章标题' }],
        articleBody: [{ required: true, message: '请输入文章标题' }]
      }
    }
  },
  methods: {
    async btnOk () {
      // 手动校验
      try {
        await this.$refs.articleForm.validate()
        if (this.article.id) {
          // 修改
          await update(this.article)
        } else {
          // 添加
          await add(this.article) // 调用添加文章接口
        }
        this.$emit('add-article') // 告诉父组件重新获取数据
        this.$emit('update:showEditAddDialog', false) // 关闭弹层
        this.$message.success(this.article.id ? '修改文章成功' : '新增文章成功')
      } catch (error) {
        console.log(error)
      }
    },
    btnCancel () { // 点击取消
      this.$emit('btnCancel')
      this.$refs.articleForm.resetFields() // 重置校验字段
      this.$emit('update:showEditAddDialog', false) // 关闭弹层
    }
  },
  computed: {
    showTitle () { // 动态标题
      return this.article.id ? '修改文章' : '新增文章'
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep.quill-editor {
  .ql-editor {
    height: 200px;
  }
}
</style>
